﻿using SIG.Basic.Extensions;
using SIG.Basic.Helper;
using SIG.Infrastructure.Extensions;
using SIG.Model;
using SIG.Model.Enums;
using SIG.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [RouteArea("Admin", AreaPrefix = "sig-admin")]
    [RoutePrefix("category")]
    public class CategoryController : Controller
    {
        // GET: Admin/Category
        private readonly ICategoryService _categoryService;


        public CategoryController(ICategoryService categoryService)
        {
            _categoryService = categoryService;
          
        }

        #region 分类
        //
        // GET: /Admin/Category/modelType
        [Route("{modelType}")]
        [Authorize(Roles = "创始人,管理员")]
        public ActionResult Index(ModelType modelType)
        {

            ViewBag.ModelType = modelType;

            ModelType Type = modelType; // ToModelType(ref modelType);
           
            ViewBag.ModelTypeName = Type.DisplayName();

            var categories = _categoryService.GetAllCategories(Type);
            return View(categories);
        }


        [Authorize(Roles = "创始人,管理员")]
        [Route("{modelType}-Add")]
        public ActionResult Add(ModelType modelType)
        {

            ViewBag.ModelType = modelType;
            ModelType Type = modelType; // ToModelType(ref modelType);

            ViewBag.ModelTypeName = Type.DisplayName();

            Category vCategory = new Category();
            vCategory.ModelType = ModelType.NEWS;
            vCategory.Active = true;
            vCategory.Importance = 0;

            GetParentCategories(Type,null);
            return View(vCategory);
        }

       


        [HttpPost]
        [Authorize(Roles = "创始人,管理员")]
        [Route("AddConfirm")]
        public JsonResult AddConfirm(Category category)
        {
            if (ModelState.IsValid)
            {
                _categoryService.Create(category);

                return Json(true, JsonRequestBehavior.DenyGet);

            }
         
                return Json(false, JsonRequestBehavior.DenyGet);
            

        }


        [Authorize(Roles = "创始人,管理员")]
        [Route("{modelType}-Edit/{id:int?}"),ActionName("Edit")]
        
        public ActionResult Edit(ModelType modelType, int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            ViewBag.ModelType = modelType;
            ModelType Type = modelType; // ToModelType(ref modelType);
            ViewBag.ModelTypeName = Type.DisplayName();

            GetParentCategories(Type,id); 
         
            Category category = _categoryService.GetById(id);
            if (category == null)
            {
                return HttpNotFound();
            }
            return View(category);
        }

        [HttpPost]
        [Authorize(Roles = "创始人,管理员")]
        [Route("EditConfirm")]
        public JsonResult EditConfirm([Bind(Include = "Id,Title,ParentId,Importance,Active,ModelType,CreatedDate,CreatedBy,UpdatedDate,UpdatedBy")]Category category)
        {

            if (ModelState.IsValid)
            {
                _categoryService.Update(category);
                return Json(true, JsonRequestBehavior.DenyGet);
            }
           
            return Json(false, JsonRequestBehavior.DenyGet);        

        }

        // DELETE: /User/DeleteSite
        [HttpPost]
        [Authorize(Roles = "创始人,管理员")]
        [Route("Delete/{id:int}")]
        public JsonResult Delete(int id)
        {

            Category vCategory = _categoryService.GetByIdWithProducts(id);

            if (vCategory != null)
            {
                if (vCategory.Products.Count > 0 || vCategory.ChildCategories.Count > 0)
                    return Json(false, JsonRequestBehavior.DenyGet);


                var category = _categoryService.GetById(id);
                _categoryService.Delete(category);


            }
            return Json(true, JsonRequestBehavior.DenyGet);

        }


        [HttpPost]
        [Authorize(Roles = "创始人,管理员")]
        [Route("Active/{id:int}")]
        public JsonResult Active(int id)
        {

            var vCategory = _categoryService.GetById(id);

            try
            {
                if (vCategory != null)
                {
                    vCategory.Active = !vCategory.Active;

                    _categoryService.Update(vCategory);
                    //_unit.SaveChanges();

                }
            }
            catch (Exception ex)
            {
                return Json(false, JsonRequestBehavior.DenyGet);
            }

            return Json(true, JsonRequestBehavior.DenyGet);

        }


        private static ModelType ToModelType(ref string modelType)
        {
            modelType = modelType.ToUpper();
            ModelType Type = (ModelType)System.Enum.Parse(typeof(ModelType), modelType);
            return Type;
        }

        private void GetParentCategories(ModelType modelType, int? id)
        {
            var parentCategories = _categoryService.GetAllCategories(modelType);
            if (id > 0)
            {
                parentCategories = parentCategories.Where(c=>c.Id!=id).ToList();
            }
         
            var lCategories = parentCategories.Select(r => new SelectListItem()
            {
                Value = r.Id.ToString(),
                Text = r.Title
            }).ToList();

            var emptyItem = new SelectListItem()
            {
                Value = "",
                Text = "--选择父级分类--"
            };

            lCategories.Insert(0, emptyItem);

            ViewBag.ParentCategories = new SelectList(lCategories, "Value", "Text");

        }

        ///// <summary>
        ///// 获取分类列表
        ///// </summary>
        ///// <returns></returns>
        //public List<SelectListItem> GetCategoryList(ModelType modelType)
        //{

        //    var OptGroups = _categoryService.GetAllCategories(modelType).Select(c => new SelectListGroup { Name = c.Title }).ToList();
        //    var categories = _categoryService.GetChildCategoriesWithParent(modelType);
        //    //   lCategories.Insert(0, new SelectListItem { Text = "--按分类过滤--", Value = "" });

        //    return (from category in categories
        //            let parId = category.ParentId.ToString()
        //            select new SelectListItem
        //            {
        //                Text = category.Title,
        //                Value = category.Id.ToString(),
        //                Group = OptGroups.FirstOrDefault(o => o.Name == category.ParentCategoryTitle)
        //                // Selected = (blogId == blog.Id)
        //            }).ToList();
        //}

        //public List<SelectListItem> GetCategoryList(int catId,ModelType modelType)
        //{
        //    var OptGroups = _categoryService.GetAllCategories(modelType).Select(c => new SelectListGroup { Name = c.Title }).ToList();
        //    var categories = _categoryService.GetChildCategoriesWithParent(modelType);
        //    List<SelectListItem> lCategories = new List<SelectListItem>();
        //    foreach (var category in categories)
        //    {
        //        var parId = category.ParentId.ToString();
        //        var sli = new SelectListItem
        //        {
        //            Text = category.Title,
        //            Value = category.Id.ToString(),
        //            Group = OptGroups.FirstOrDefault(o => o.Name == category.ParentCategoryTitle),
        //            Selected = (catId == category.Id)
        //        };

        //        lCategories.Add(sli);

        //    }
        //    lCategories.Insert(0, new SelectListItem { Text = "--按分类过滤--", Value = "" });

        //    return lCategories;
        //}

        #endregion 
    }
}